package com.qhsolution.object;

import java.util.ArrayList;

import com.qhsolution.adapter.WordArrayAdapter;
import com.qhsolution.bdict.DetailActivity;
import com.qhsolution.bdict.MainActivity;
import com.qhsolution.bdict.R;
import com.qhsolution.dbhelper.DataHelper;
import com.qhsolution.object.Word;

import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.FilterQueryProvider;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.SimpleCursorAdapter.CursorToStringConverter;
import android.widget.TextView;

public class Lookup extends Fragment {
	
	final static int[] to = new int[] { android.R.id.text1, android.R.id.text2 };
    final static String[] from = new String[] { "eng","name" };
    
    SimpleCursorAdapter mAdapter;
	
	DataHelper dbHelper;
	
	int numRow = 0;
	int offset = 0;
	
	WordArrayAdapter adapter = null;
	
	ArrayAdapter<String> adapterAutoComplete = null;
	
	ArrayList<Word> arrWord = new ArrayList<Word>();
	
	ArrayList<String> arrAutoComplete = new ArrayList<String>();
	
	AutoCompleteTextView txtSearch;
	
	ListView lv;
	
	Button btnSearch;
	boolean isSearch = false;
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		final ViewGroup container2 = container;
		View rootView=inflater.inflate(R.layout.activity_lookup, container,false);
		dbHelper = new DataHelper(container.getContext());
		lv=(ListView) rootView.findViewById(R.id.listWord);
		lv.setOnScrollListener(new OnScrollListener() {

			@Override
			public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
				// TODO Auto-generated method stub
				int lastInScreen = firstVisibleItem + visibleItemCount; 
				if(lastInScreen == totalItemCount)
				{
					if(adapter != null && !isSearch)
					{
						LoadData();					
						adapter.notifyDataSetChanged();
					}
				}
			}

			@Override
			public void onScrollStateChanged(AbsListView arg0, int arg1) {
				// TODO Auto-generated method stub
				
			}
			
		});
		
		txtSearch = (AutoCompleteTextView) rootView.findViewById(R.id.txtSearch);
		
		mAdapter = new SimpleCursorAdapter(container.getContext(), android.R.layout.simple_list_item_2, null, from, to, 0);
		
		txtSearch.setAdapter(mAdapter);		
		
		mAdapter.setFilterQueryProvider(new FilterQueryProvider() {
			 public Cursor runQuery(CharSequence str) {
				 return getCursor(str);
		} });
			  
		mAdapter.setCursorToStringConverter(new CursorToStringConverter() {
			
			 public CharSequence convertToString(Cursor cur) {
				 int index = cur.getColumnIndex("eng");
				 return cur.getString(index);
			 }
		});
		
		//LoadAutoCompleteData();
		//adapterAutoComplete = new ArrayAdapter<String>(getActivity(),
		//		android.R.layout.simple_list_item_1, arrAutoComplete);
		//txtSearch.setAdapter(adapterAutoComplete);
		
		LoadData();
		adapter=new WordArrayAdapter(getActivity(), R.layout.gridview_word, arrWord);
		adapter.notifyDataSetChanged();
		lv.setAdapter(adapter);
		lv.setOnItemClickListener(new OnItemClickListener(){

			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				// TODO Auto-generated method stub
				//Log.d("PositionView", String.valueOf(position));
				Intent intent = new Intent(container2.getContext(), DetailActivity.class);
				TextView txtId = (TextView) view.findViewById(R.id.txtId);
				String Id = txtId.getText().toString();
				intent.putExtra(MainActivity.WORD_ID, Id);
				startActivity(intent);
			}
			
		});
		lv.setOnTouchListener(new OnTouchListener() {
			@Override
			public boolean onTouch(View arg0, MotionEvent arg1) {
				// TODO Auto-generated method stub
				hideSoftKeyboard(getActivity());
				return false;
			}
		});
		
		btnSearch = (Button) rootView.findViewById(R.id.btnSearch);
		btnSearch.setOnClickListener(new OnClickListener(){

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				LoadDataByKeyword(txtSearch.getEditableText().toString());
				adapter.notifyDataSetChanged();
			}
			
		});
		
		return rootView;
	}
	
	public void LoadDataByKeyword(String Keyword)
	{
		if(Keyword.trim()!="")
		{
			dbHelper.openDataBase();
			arrWord.clear();
			
			Cursor c = dbHelper.getSelect("word", null, "eng LIKE ? OR name LIKE ?", new String[]{"%" + Keyword.trim() + "%","%" + Keyword.trim() + "%"}, null, null, "eng ASC");
			if(c.getCount()>0)
			{
				isSearch = true;
				c.moveToFirst();
				while(!c.isAfterLast())
				{
					String name = "";
					if(c.getString(1)!=null)
					{
						name = c.getString(1);
						name = name.trim();
					}
					String eng = "";
					if(c.getString(7)!=null)
					{
						eng = c.getString(7);
						eng = eng.trim();
					}
					
					String description = "";
					if(c.getString(2)!=null)
					{
						description = c.getString(2);
						description = description.trim();
					}
					
					Word word = new Word(Integer.parseInt(c.getString(0)),name, description, c.getString(3), eng, Integer.parseInt(c.getString(4)), Integer.parseInt(c.getString(5)), Integer.parseInt(c.getString(6)));
					arrWord.add(word);
					c.moveToNext();
				}
			}
			dbHelper.close();
		}
		else
		{
			isSearch = false;
		}
	}
	
	public void LoadData(){
		dbHelper.openDataBase();
		numRow = numRow + 20;
		Cursor c = dbHelper.getSelect("word", null, null, null, null, null, "eng ASC",String.valueOf(offset)+","+String.valueOf(numRow));
		if(c.getCount()>0 && arrWord.size() <= c.getCount())
		{
			c.moveToFirst();
			while(!c.isAfterLast())
			{
				String name = "";
				if(c.getString(1)!=null)
				{
					name = c.getString(1);
					name = name.trim();
				}
				String eng = "";
				if(c.getString(7)!=null)
				{
					eng = c.getString(7);
					eng = eng.trim();
				}
				
				String description = "";
				if(c.getString(2)!=null)
				{
					description = c.getString(2);
					description = description.trim();
				}
				
				Word word = new Word(Integer.parseInt(c.getString(0)),name, description, c.getString(3), eng, Integer.parseInt(c.getString(4)), Integer.parseInt(c.getString(5)), Integer.parseInt(c.getString(6)));
				arrWord.add(word);
				c.moveToNext();
			}
		}
		offset = offset + 20;
		dbHelper.close();
	}
	
	public void LoadAutoCompleteData(){
		dbHelper.openDataBase();
		Cursor c = dbHelper.getSelect("word", null, null, null, null, null, null);
		if(c.getCount()>0)
		{
			c.moveToFirst();
			while(!c.isAfterLast())
			{
				String text = "";
				if(c.getString(7)!=null)
				{
						
					text = c.getString(7);
					text = text.trim();
				}
				arrAutoComplete.add(text);
				c.moveToNext();
			}
		}
		dbHelper.close();
	}
	
	@Override
	public void onResume(){
		//Reload the Data
		if(!arrWord.isEmpty())
		{
			arrWord.clear();
			numRow = 0;
			offset = 0;
			LoadData();
			adapter.notifyDataSetChanged();
		}
//		if(!arrAutoComplete.isEmpty())
//		{
//			arrAutoComplete.clear();
//			LoadAutoCompleteData();
//			adapterAutoComplete.notifyDataSetChanged();
//		}
		super.onResume();
	}
	
	@Override
	public void onPause()
	{
		super.onPause();
		if(dbHelper.openDataBase())
		{
			dbHelper.close();
		}
	}

	@Override
    public void setMenuVisibility(final boolean visible) {
        super.setMenuVisibility(visible);
        if (visible) {
        	//Reload the Data
        	if(!arrWord.isEmpty())
    		{
    			arrWord.clear();
    			numRow = 0;
    			offset = 0;
    			LoadData();
    			adapter.notifyDataSetChanged();
    		}
        	
//        	if(!arrAutoComplete.isEmpty())
//    		{
//    			arrAutoComplete.clear();
//    			LoadAutoCompleteData();
//    			adapterAutoComplete.notifyDataSetChanged();
//    		}
            Log.d("LookupTab","true");
        }
    }
	
	
	
	public Cursor getCursor(CharSequence str) {
		
		dbHelper.openDataBase();
		String columnSearch = "eng";
		Cursor c = dbHelper.getSelect("word", null, columnSearch + " LIKE ? OR name LIKE ?", new String[]{"%" + str + "%","%" + str + "%"}, null, null, columnSearch + " ASC");
		return c;
		
	}
	
	public static void hideSoftKeyboard(Activity activity)
	{
		InputMethodManager inputMethodManager = (InputMethodManager) activity
	    .getSystemService(Activity.INPUT_METHOD_SERVICE);
		inputMethodManager.hideSoftInputFromWindow(activity.getCurrentFocus().getWindowToken(), 0);
	}
	
}
